from PySide6.QtCore import QThread, Signal, SIGNAL
from elasticsearch import Elasticsearch, ElasticsearchException
from PySide6 import QtCore
import logging


class LoadElasticsearchIndexListThread(QThread):
    success = Signal(list)
    failure = Signal()

    def __init__(self, parent=None, host=None, username=None, password=None):
        super(LoadElasticsearchIndexListThread, self).__init__(parent)
        self.host = host
        self.password = password
        self.username = username

    def run(self):
        flag, result = getIndexList(self.host, self.username, self.password)
        print(flag, result)
        if flag:
            self.success.emit(result)
        else:
            self.failure.emit()


def getIndexList(host=None, username=None, password=None):
    timeout = 10
    flag = True
    data = None
    try:
        if username is None:
            es = Elasticsearch(host, sniff_timeout=timeout)
        else:
            es = Elasticsearch(
                [host],
                http_auth=(username, password),
                sniff_timeout=timeout
            )
        data = []
        indexList = es.indices.get_alias().keys()
        print(indexList)
        for index in indexList:
            if '.' not in index:
                data.append(index)
    except BaseException as e:
        logging.error('连接异常', e)
        data = "Elastic连接异常"
        flag = False
    print(data)
    return flag, data


# 发布数据


class Publish2Elasticsearch(QThread):

    def __init__(self, parent=None, data=None, host=None, username=None, password=None, index=None):
        super(Publish2Elasticsearch, self).__init__(parent)
        self.data = data
        if username is None:
            self.es = Elasticsearch(host)
        else:
            self.es = Elasticsearch(
                [host],
                http_auth=(username, password)
            )

    def run(self):
        if self.data is None:
            return
